package com.econ.powercloud.ems.timing.report;

import com.econ.powercloud.ems.aop.TimingRetryValid;
import com.econ.powercloud.ems.common.util.URIEncoder;
import com.econ.powercloud.ems.config.ApplicationContextConfiguration;
import com.econ.powercloud.ems.dal.entity.PrometheusMonitorItem;
import com.econ.powercloud.ems.service.dao.PrometheusMonitorItemDAO;
import com.econ.powercloud.ems.timing.report.prometheus.callback.PrometheusCpuRateCallback;
import com.econ.powercloud.ems.util.AsyncHttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class PrometheusTask {

    public static final String PROMETHEUS_TASK = "prometheus-task";

    @Autowired
    PrometheusMonitorItemDAO prometheusMonitorItemDAO;

    @Autowired
    PrometheusCpuRateCallback prometheusCpuRateCallback;

    @Scheduled(cron = "0 */5 * * * ?")
    @TimingRetryValid(lockName = PROMETHEUS_TASK,timeOutSecond = 60L)
    public void execute(){
        List<PrometheusMonitorItem> prometheusMonitorItemList = prometheusMonitorItemDAO.findAll();
        for(PrometheusMonitorItem prometheusMonitorItem : prometheusMonitorItemList){
            String callback = prometheusMonitorItem.getCallback();
            if(StringUtils.isBlank(callback)){
                continue;
            }
            Object bean = ApplicationContextConfiguration.getBean(callback);
            if(bean == null){
                continue;
            }

            if(bean instanceof AsyncHttpClientUtil.StringFutureCallback){
                String url = prometheusMonitorItem.getUrl();
                String params = URIEncoder.encodeURIComponent(prometheusMonitorItem.getParams());
                System.out.println(url);
                System.out.println(params);
                AsyncHttpClientUtil.post(url, params, ContentType.APPLICATION_FORM_URLENCODED, (AsyncHttpClientUtil.StringFutureCallback)bean);
            }
        }
    }
}